package logic

import (
	"context"
	"database/sql"
	"github.com/dtm-labs/dtmcli"
	"github.com/dtm-labs/dtmgrpc"
	"go-zero-project/services/product/rpc/internal/mapper"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"go-zero-project/services/product/rpc/internal/svc"
	"go-zero-project/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DecrStockRevertLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDecrStockRevertLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DecrStockRevertLogic {
	return &DecrStockRevertLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DecrStockRevertLogic) DecrStockRevert(in *pb.DecrStockRequest) (*pb.DecrStockResponse, error) {
	// 1.获取子事务屏障对象
	branchBarrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, err
	}
	// 2.开启子事务屏障
	dbEngin := l.svcCtx.DBEngin
	db, err := dbEngin.DB()
	if err != nil {
		return nil, err
	}
	err = branchBarrier.CallWithDB(db, func(tx *sql.Tx) error {
		productMapper := mapper.NewProductMapper()
		resultStockResult, resultStockErr := productMapper.TxAdjustStock(l.ctx, tx, in.Id, 1)
		if resultStockErr != nil {
			return resultStockErr
		}
		// 更新回去失败
		affected, err := resultStockResult.RowsAffected()
		if err == nil && affected == 0 {
			return dtmcli.ErrFailure
		}
		return err
	})
	if err == dtmcli.ErrFailure {
		return nil, status.Error(codes.Aborted, dtmcli.ResultFailure)
	}
	if err != nil {
		return nil, err
	}

	return &pb.DecrStockResponse{}, nil
}
